package top.api.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.api.annotation.SystemLog;
import top.api.common.ResponseResult;
import top.api.domain.entity.LoginUserDetails;
import top.api.domain.entity.Menu;
import top.api.domain.entity.User;
import top.api.domain.vo.AdminUserInfoVo;
import top.api.domain.vo.RoutersVo;
import top.api.domain.vo.UserInfoVo;
import top.api.service.AdminLoginService;
import top.api.service.MenuService;
import top.api.service.RoleService;
import top.api.utils.BeanCopyUtils;
import top.api.utils.SecurityUtils;

import java.util.List;

@RestController
@Api(tags = "登录")
public class AdminLoginController {

    @Autowired
    private AdminLoginService adminLoginService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private RoleService roleService;

    /**
     * 登录
     * @param user
     * @return
     */
    @PostMapping("/user/login")
    @ApiOperation(value = "login",notes = "只需要userName, password 两个参数")
    @SystemLog("登录操作")
    public ResponseResult login(@RequestBody User user){
        return adminLoginService.login(user);
    }

    /**
     * 查询用户信息和菜单权限
     * @return
     */
    @GetMapping("/getInfo")
    @ApiOperation(value = "查询用户信息和菜单权限")
    public ResponseResult getInfo(){
        // 获取当前用户(type: 1 超级管理员方法所有权限)
        LoginUserDetails loginUser = SecurityUtils.getLoginUser();
        // 查询对应的角色
        List<String> roleKeys = roleService.selectRoleKey(loginUser.getUser());
        // 查询对应的菜单权限
        List<String> perms = menuService.selectPerms(loginUser.getUser());

        // 拷贝一下
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(loginUser.getUser(), UserInfoVo.class);
        AdminUserInfoVo adminUserInfoVo = new AdminUserInfoVo(perms,roleKeys,userInfoVo);

        return ResponseResult.okResult(adminUserInfoVo);
    }

    /**
     * 查询菜单
     * @return
     */
    @GetMapping("getRouters")
    public ResponseResult<RoutersVo> getRouters(){
        User user = SecurityUtils.getLoginUser().getUser();
        //查询menu 结果是tree的形式
        List<Menu> menus = menuService.selectRouterMenuTree(user);
        //封装数据返回
        return ResponseResult.okResult(new RoutersVo(menus));
    }

}


